/* 
 * shamefully copy from AnFetion.
 * more see: http://code.google.com/p/anfetion/
 */
package person.bangbang.im.Androidgin.Fetion;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import person.bangbang.im.Androidgin.Fetion.TcpSendAndReceive.IPackageReceivedHandler;
import android.util.Log;

public class RemotePackageHandler extends SIPCBase implements IPackageReceivedHandler {
    private static final String TAG = "RemotePackageHandler";
    public int FETION_NOTIFYCATION_ID = 100;
    
    // TODO don't need this 
//    private FetionService context;
    private FetionProtocol protocol;
    private FetionUri fetionid;
    private ArrayList<FetionFriend> buddies = null;

    private ArrayList<FetionFriend> getBuddies() {
        if (buddies == null) {
//            buddies = context.getReserveNotify().getBuddies();
        	buddies = protocol.getFetionFriend();
        }
        return buddies;
    }

    // private message = new FetionMessage();

    public RemotePackageHandler(FetionProtocol protocol, FetionUri fetionid, TcpSendAndReceive connection,
//    public RemotePackageHandler(Context context, FetionUri fetionid, TcpSendAndReceive connection,
            SerialManager serialManager) {
        super(serialManager, connection);
//        this.context = context;
        this.protocol = protocol;
        this.fetionid = fetionid;
    }

    @Override
    public boolean execute() {

        return false;
    }

    public boolean received(FetionSIPC sipc) {
        try {
            if (sipc.isResponse()) return true;
            String cmd = sipc.getRequestCmdLine().cmd;
            if (cmd.equals("M")) {// 收到短消息
                // message.from
                String from = sipc.GetHeaderValue("F");

                FetionFriend fetionFriend = MiscUtil.getFriend(from, getBuddies());

                if (fetionFriend == null) {
                	Log.e(TAG,"Receive message whose sender is not in buddies' list");
//                	protocol.onIMError(fetionFriend, -1, "Receive message whose sender is not in buddies' list:" + from);
//                    context.setLastError("Receive message whose sender is not in buddies' list:" + from);
                    return false;
                }

                // ((FetionService)context).setLastError(sipc.body); //Tiger. Debug

                // 去掉字体信息
                Pattern pattern = Pattern.compile("<Font(.*?)>(.*?)</Font>");
                Matcher matcher = pattern.matcher(sipc.body);
                if (matcher.find()) sipc.body = matcher.group(2);
                sipc.body = StrUtil.xmlToString(sipc.body);

                from = fetionFriend.getName();
                
                // we don't need this any more, bcz the Message will contain 
                // all details about it. bangbang.song@gmail.com
//                String msg = from + " : " + sipc.body;
                String msg = sipc.body;
                fetionFriend.addMessage(from, sipc.body);
                fetionFriend.lastMessage = sipc.body;
                
                Log.d(TAG, "Rcvd a message from: " + from + " msg: " + msg);
                protocol.onRcvdIM(from, msg);
                
                // bangbang.song@gmail.com
                // delegate to Service to do it.
                // FIXME: a temple solution.
//                context.saveMessage(StrUtil.getPeopleId(fetionFriend.Uri), StrUtil.getPeopleId(context
//                        .getMyself().Uri), sipc.body);
//
//                SendSMSActivity chatActivity = FetionService.chatActivity;
//
//                if (chatActivity != null && chatActivity.getFetionFriend() == fetionFriend) {
//                    chatActivity.onReceiveMessage();
//                } else {
//                    if (Settings.DEBUG) Log.d(TAG, msg);
//                    int id = fetionFriend.notifyID;
//                    if (id <= 0) {
//                        id = FETION_NOTIFYCATION_ID++;
//                    }
//                    // ((FetionService)context).setlastReceivedMessage(sipc.body); //Tiger.
//                    // 保存消息，用于在send框显示
//                    Notification info = new Notification(R.drawable.fetion, msg, System.currentTimeMillis());
//                    info.ledARGB = 0xff00ff00;
//                    info.ledOnMS = 1000;
//                    info.ledOffMS = 3000;
//                    info.flags |= Notification.FLAG_SHOW_LIGHTS;
//                    // info.flags = Notification.FLAG_SHOW_LIGHTS;
//                    // info.ledOnMS = 1000;
//                    // info.ledOffMS = 2000;
//                    // info.defaults = Notification.DEFAULT_LIGHTS;
//                    // .DEFAULT_SOUND;
//                    // R.raw.newmessage
//                    // context.getResources().
//                    // info.sound = Uri.
//                    Intent contentIntent = new Intent(context, SendSMSActivity.class);
//                    contentIntent.putExtra("uri", fetionFriend.Uri);
//                    contentIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
//                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
//                    // .setData(Uri.parse(sipc
//                    // .GetHeaderValue("F")/* + "^" + String.valueOf(id) */));
//                    PendingIntent appIntent = PendingIntent.getActivity(context, 0, contentIntent,
//                            PendingIntent.FLAG_ONE_SHOT);
//                    info.setLatestEventInfo(context, msg, null, appIntent);
//                    MiscUtil.getNotificationManager(context).notify(id, info);
//
//                    // message.fetionFriend.setOnStatusBar(true);
//                    fetionFriend.notifyID = id;
//                    // ((FetionService) context).getFriendsSentNewMessage().add(fetionFriend);
//                    MediaPlayer.create(context.getApplicationContext(), R.raw.newmessage).start();
//
//                    MiscUtil.notifyReceival(context);
//                }

                ArrayList<FetionSIPC.HeaderPair> headers = new ArrayList<FetionSIPC.HeaderPair>();

                headers.add(new FetionSIPC.HeaderPair("F", sipc.GetHeaderValue("F")));
                headers.add(new FetionSIPC.HeaderPair("I", sipc.GetHeaderValue("I")));
                headers.add(new FetionSIPC.HeaderPair("Q", sipc.GetHeaderValue("Q")));
                headers.add(new FetionSIPC.HeaderPair("L", String.valueOf(0)));
                FetionSIPC res = new FetionSIPC("SIP-C/2.0 200 OK", headers, "");
                connection.SendSIPC(res);
            } else if (cmd.equals("BN")) {// 收到通知
//                if (sipc.GetHeaderValue("N").equals("contact")) {
//                    // 加好友申请
//                    MessageXml.AddBuddyApplicationMessage cm = new MessageXml.AddBuddyApplicationMessage();
//                    if (cm.parseXml(sipc.body)) {
//                        String msg = "我是" + cm.desc + ", 正在用中国移动飞信业务, 想加您为好友";
//                        Notification info = new Notification(R.drawable.fetion, msg, System
//                                .currentTimeMillis());
//                        info.defaults = Notification.DEFAULT_ALL;
//                        Intent contentIntent = new Intent(context, HandleContactRequest.class);
//                        Bundle bundle = new Bundle();
//                        bundle.putSerializable("contact", cm);
//                        bundle.putString("sipc", sipc.toString());
//                        bundle.putString("message", msg);
//                        bundle.putInt("notify_id", FETION_NOTIFYCATION_ID);
//                        contentIntent.putExtras(bundle);
//                        PendingIntent appIntent = PendingIntent.getActivity(context, 0, contentIntent, 0);
//                        info.setLatestEventInfo(context, "好友申请，点击批准", msg, appIntent);
//                        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE))
//                                .notify(FETION_NOTIFYCATION_ID++, info);
//                        return true;
//                    }
//
//                    // 好友信息更新
//                    MessageXml.UpdateBuddyMessage ubm = new MessageXml.UpdateBuddyMessage(getBuddies());
//                    if (ubm.parseXml(sipc.body)) {
//                        MiscUtil.notifyFriendChange(context);
//                        return true;
//                    }
//                    
//                    // 好友信息更新
//                    MessageXml.ServiceResultMessage srm = new MessageXml.ServiceResultMessage(getBuddies());
//                    if (srm.parseXml(sipc.body)) {
//                        MiscUtil.notifyFriendChange(context);
//                        return true;
//                    }
//
//                    Log.w(TAG, "Contact unparsed! :" + sipc.body);
//                } else if (sipc.GetHeaderValue("N").equals("permission")) {
//                    Pattern pattern = Pattern.compile("<event type=\"BuddyPermissionChanged\">"
//                            + "<permissions version=\"(.*)\"><permission "
//                            + "uri=\"(.*?)\" values=\"identity=1;\"/></permissions></event>");
//                    Matcher matcher = pattern.matcher(sipc.body);
//                    if (matcher.find()) {
//                        String uri = matcher.group(2);
//                        FetionFriend fetionFriend = MiscUtil.getFriend(uri, getBuddies());
//                        if (fetionFriend == null) {
//                            fetionFriend = new FetionFriend();
//                            fetionFriend.Uri = uri;
//                            //fetionFriend.FriendName = null;
//                            this.buddies.add(fetionFriend);
//                            MiscUtil.notifyFriendChange(context);
//                        }
//                    }
//                }

            } else if (cmd.equals("I")) { // 会话邀请

//                ArrayList<FetionSIPC.HeaderPair> headers = new ArrayList<FetionSIPC.HeaderPair>();
//                headers.add(new FetionSIPC.HeaderPair("I", sipc.GetHeaderValue("I")));
//                headers.add(new FetionSIPC.HeaderPair("Q", sipc.GetHeaderValue("Q")));
//                headers.add(new FetionSIPC.HeaderPair("F", sipc.GetHeaderValue("F")));
//                headers.add(new FetionSIPC.HeaderPair("K", "text/plain"));
//
//                String body = "v=0\r\no=-0 0 IN " + this.connection.getLocalAddress() + ":"
//                        + String.valueOf(this.connection.getLocalPort()) + "\r\ns=session\r\nc=IN IP4 "
//                        + this.connection.getLocalAddress() + ":"
//                        + String.valueOf(this.connection.getLocalPort())
//                        + "\r\nt=0 0\r\nm=message 11181 sip " + this.fetionid.toString();
//                headers.add(new FetionSIPC.HeaderPair("L", StrUtil.getLength(body)));
//                FetionSIPC res = new FetionSIPC("SIP-C/2.0 200 OK", headers, body);
//                connection.SendSIPC(res);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    

}
